"""
简化的文档转换器
- DOCX转换：使用Pandoc
- PDF转换：使用WeasyPrint
"""
import subprocess
import tempfile
import os
import uuid
from typing import Optional
import markdown
import re
from datetime import datetime


class DocumentConverter:
    def __init__(self):
        self.pandoc_available = self._check_pandoc()
        # 在Docker环境中禁用PDF功能以简化部署
        if self._is_docker_env():
            self.weasyprint_available = False
        else:
            self.weasyprint_available = self._check_weasyprint()
    
    def _is_docker_env(self) -> bool:
        """检查是否在Docker环境中运行"""
        return (os.path.exists('/.dockerenv') or 
                os.environ.get('DOCKER_ENV') == 'true' or
                os.path.exists('/proc/1/cgroup') and 'docker' in open('/proc/1/cgroup').read())
    
    def _check_pandoc(self) -> bool:
        """检查Pandoc是否可用"""
        try:
            result = subprocess.run(['pandoc', '--version'], 
                                  capture_output=True, text=True, timeout=5)
            return result.returncode == 0
        except:
            return False
    
    def _check_weasyprint(self) -> bool:
        """检查WeasyPrint是否可用"""
        try:
            import weasyprint
            return True
        except ImportError:
            return False
    
    def _generate_filename(self, user_question: Optional[str], extension: str) -> str:
        """根据用户问题和时间生成文件名"""
        # 获取当前时间
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        if user_question and user_question.strip():
            # 清理用户问题，移除特殊字符，保留中文、英文、数字
            clean_question = re.sub(r'[^\w\u4e00-\u9fff\s]', '', user_question.strip())
            # 替换空格为下划线，限制长度
            clean_question = re.sub(r'\s+', '_', clean_question)[:30]
            if clean_question:
                return f"{clean_question}_{timestamp}.{extension}"
        
        # 如果没有用户问题或清理后为空，使用默认名称
        return f"AI对话导出_{timestamp}.{extension}"
    
    def convert_to_docx(self, markdown_text: str, title: Optional[str] = None, user_question: Optional[str] = None) -> str:
        """
        使用Pandoc转换Markdown为DOCX
        """
        if not self.pandoc_available:
            raise Exception("DOCX转换需要安装Pandoc")
        
        return self._pandoc_convert_docx(markdown_text, title, user_question)
    
    def convert_to_pdf(self, markdown_text: str, title: Optional[str] = None, user_question: Optional[str] = None) -> str:
        """
        使用WeasyPrint转换为PDF
        """
        if self._is_docker_env():
            raise Exception("Docker环境中PDF功能已禁用，仅支持DOCX转换")
        
        if not self.weasyprint_available:
            raise Exception("PDF转换需要安装WeasyPrint")
        
        return self._weasyprint_convert_pdf(markdown_text, title, user_question)
    
    def _pandoc_convert_docx(self, markdown_text: str, title: Optional[str], user_question: Optional[str] = None) -> str:
        """使用Pandoc转换为DOCX"""
        temp_md_file = None
        output_file = None
        
        try:
            # 创建临时Markdown文件
            with tempfile.NamedTemporaryFile(mode='w', suffix='.md', 
                                           delete=False, encoding='utf-8') as f:
                f.write(markdown_text)
                temp_md_file = f.name
            
            # 生成输出文件路径
            filename = self._generate_filename(user_question, 'docx')
            
            # 确保temp目录存在
            os.makedirs("temp", exist_ok=True)
            output_file = os.path.join("temp", filename)
            
            # 构建Pandoc命令
            pandoc_cmd = [
                'pandoc',
                temp_md_file,
                '-o', output_file,
                '--from', 'markdown+pipe_tables+backtick_code_blocks+fenced_code_attributes',
                '--to', 'docx',
                '--standalone',
            ]
            
            # 执行转换
            result = subprocess.run(pandoc_cmd, capture_output=True, text=True, timeout=60)
            
            if result.returncode != 0:
                error_msg = result.stderr or "Pandoc转换失败"
                raise Exception(f"Pandoc转换错误: {error_msg}")
            
            # 检查输出文件是否生成
            if not os.path.exists(output_file):
                raise Exception("转换完成但未找到输出文件")
            
            return output_file
            
        except subprocess.TimeoutExpired:
            raise Exception("Pandoc转换超时")
        finally:
            # 清理临时文件
            if temp_md_file and os.path.exists(temp_md_file):
                try:
                    os.remove(temp_md_file)
                except:
                    pass
    
    def _weasyprint_convert_pdf(self, markdown_text: str, title: Optional[str], user_question: Optional[str] = None) -> str:
        """使用WeasyPrint转换HTML为PDF"""
        import weasyprint
        
        # 将Markdown转换为HTML
        html_content = markdown.markdown(
            markdown_text,
            extensions=['tables', 'fenced_code', 'codehilite', 'toc']
        )
        
        # 创建完整的HTML页面
        full_html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>文档导出</title>
    <style>
        @page {{
            size: A4;
            margin: 20mm;
        }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
        }}
        h1, h2, h3, h4, h5, h6 {{
            color: #2c3e50;
            margin-top: 24px;
            margin-bottom: 16px;
            page-break-after: avoid;
        }}
        h1 {{ font-size: 2em; }}
        h2 {{ font-size: 1.5em; }}
        h3 {{ font-size: 1.25em; }}
        p {{ 
            margin-bottom: 16px;
            orphans: 2;
            widows: 2;
        }}
        code {{
            background: #f1f3f4;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 0.9em;
        }}
        pre {{
            background: #f8f9fa;
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            padding: 16px;
            margin: 16px 0;
            page-break-inside: avoid;
        }}
        pre code {{
            background: none;
            padding: 0;
            border-radius: 0;
        }}
        blockquote {{
            border-left: 4px solid #ddd;
            margin: 16px 0;
            padding: 0 16px;
            color: #666;
            page-break-inside: avoid;
        }}
        table {{
            border-collapse: collapse;
            width: 100%;
            margin: 16px 0;
            page-break-inside: avoid;
        }}
        th, td {{
            border: 1px solid #ddd;
            padding: 8px 12px;
            text-align: left;
        }}
        th {{
            background: #f8f9fa;
            font-weight: bold;
        }}
        ul, ol {{
            margin: 16px 0;
            padding-left: 24px;
        }}
        li {{
            margin: 4px 0;
        }}
    </style>
</head>
<body>
    {html_content}
</body>
</html>"""
        
        # 生成输出PDF文件路径
        filename = self._generate_filename(user_question, 'pdf')
        output_file = os.path.join("temp", filename)
        
        # 确保temp目录存在
        os.makedirs("temp", exist_ok=True)
        
        try:
            # 使用WeasyPrint生成PDF
            weasyprint.HTML(string=full_html).write_pdf(output_file)
            
            # 检查输出文件是否生成
            if not os.path.exists(output_file):
                raise Exception("转换完成但未找到输出文件")
            
            return output_file
            
        except Exception as e:
            raise Exception(f"WeasyPrint转换错误: {str(e)}")
    
    def get_status(self) -> dict:
        """获取转换器状态"""
        return {
            "pandoc_available": self.pandoc_available,
            "weasyprint_available": self.weasyprint_available,
            "docx_method": "Pandoc" if self.pandoc_available else "不可用",
            "pdf_method": "WeasyPrint" if self.weasyprint_available else "不可用"
        }


# 全局转换器实例
_converter = DocumentConverter()

def convert_to_docx(markdown_text: str, title: Optional[str] = None, user_question: Optional[str] = None) -> str:
    """转换Markdown为DOCX"""
    return _converter.convert_to_docx(markdown_text, title, user_question)

def convert_to_pdf(markdown_text: str, title: Optional[str] = None, user_question: Optional[str] = None) -> str:
    """转换Markdown为PDF"""
    return _converter.convert_to_pdf(markdown_text, title, user_question)

def get_converter_status() -> dict:
    """获取转换器状态"""
    return _converter.get_status()

def is_pandoc_available() -> bool:
    """检查Pandoc是否可用"""
    return _converter.pandoc_available

def is_pdf_available() -> bool:
    """检查PDF转换是否可用"""
    return _converter.weasyprint_available